package InterviewTest.q0404_isBalanced;

import CommonClass.Common.TreeNode;
public class Solution {
    /*
    考虑使用一个全局变量res来记录是否出现非平衡状态
    每次dfs中都会计算当前node左右两边的层高是否出现绝对值差大于1的情况
     */
    boolean res = true;
    public boolean isBalanced(TreeNode root) {
        dfs(root,0);
        return res;
    }

    private int dfs(TreeNode node, int level) {
        if (node == null) {
            return 0;
        }
        int left = dfs(node.left, level + 1);
        int right = dfs(node.right, level + 1);
        if (Math.abs(left - right) > 1) {
            res = false;
        }
        return Math.max(left,right) + 1;
    }
}
